package com.yequan.process;

import com.sun.jna.Platform;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

/**
 * @author yequan
 * @date 2019/12/11
 */
public class ProcessUtil {

    /**
     * 获取进程id
     *
     * @param process
     * @return
     */
    public static String getProcessId(Process process) {
        long pid = -1;
        Field field = null;
        try {
            if (Platform.isWindows()) {
                field = process.getClass().getDeclaredField("handle");
                field.setAccessible(true);
                pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(process));
            } else if (Platform.isLinux() || Platform.isAIX()) {
                Class<?> clazz = Class.forName("java.lang.UNIxProcess");
                field = clazz.getDeclaredField("pid");
                pid = ((Integer) field.get(process));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(pid);
    }

    /**
     * 根据pid关闭进程
     *
     * @param pid
     * @return
     */
    public static boolean killProcessById(String pid) {
        if (null == pid || "-1".equals(pid)) {
            throw new RuntimeException("pid = " + pid);
        }
        String command = null;
        Process process = null;
        BufferedReader reader = null;
        boolean result = false;
        if (Platform.isWindows()) {
            command = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
        } else if (Platform.isLinux() || Platform.isAIX()) {
            command = "kill -9 " + pid;
        }
        try {
            process = Runtime.getRuntime().exec(command);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            result = true;
        } catch (IOException e) {
            System.err.println("关闭进程" + pid + "失败");
            e.printStackTrace();
        } finally {
            if (null != process) {
                process.destroy();
            }
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
